package models

import (
	"fmt"
	"ginstudydemo.com/main/dao"
	"github.com/jinzhu/copier"
	"time"
)

// GetRolePageList 获取角色分页列表相关数据
func GetRolePageList(query SysRolePageListParams, pageParams PaginationParams) ([]SysRolePageListSelect, int64, int, int, error) {

	var roles []SysRolePageListSelect
	var total int64

	//==>  Preparing: SELECT COUNT(*) AS total FROM sys_role WHERE is_deleted = 0 AND ((name LIKE ? OR code LIKE ?) AND code <> ?)
	//==> Parameters: %1%(String), %1%(String), ROOT(String)

	//==>  Preparing: SELECT id, name, code, sort, status, data_scope, create_by, update_by, create_time, update_time, is_deleted FROM sys_role WHERE is_deleted = 0 AND ((name LIKE ? OR code LIKE ?) AND code <> ?) LIMIT ?
	//==> Parameters: %1%(String), %1%(String), ROOT(String), 10(Long)
	//<==    Columns: id, name, code, sort, status, data_scope, create_by, update_by, create_time, update_time, is_deleted

	// 主查询用于获取分页数据
	model := dao.Db.Debug().Table("sys_role").
		Select("id, name, code, sort, status, data_scope, create_by, update_by, create_time, update_time, is_deleted").
		Where("is_deleted = 0").
		Where("code <> ?", "root")

	// 如果传入了查询条件，则加入模糊查询
	if query.Keywords != "" {
		model = model.Where("(name LIKE ? OR code LIKE ?)", "%"+query.Keywords+"%", "%"+query.Keywords+"%")
	}

	//if query.Status != "" {
	//	model = model.Where("status = ?", query.Status)
	//}

	if query.StartDate != "" && query.EndDate != "" {
		model = model.Where("create_time >= ? AND create_time <= ?", query.StartDate, query.EndDate)
	}

	// 获取总记录数
	if err := model.Count(&total).Error; err != nil {
		return nil, 0, 0, 0, err
	}
	fmt.Println("-------")

	fmt.Println(total)
	fmt.Println("-------")
	// 添加分页条件
	offset := (pageParams.PageNum - 1) * pageParams.PageSize
	model = model.Limit(pageParams.PageSize).Offset(offset)

	// 执行查询获取分页数据
	if err := model.Scan(&roles).Error; err != nil {
		return nil, 0, 0, 0, err
	}

	return roles, total, pageParams.PageNum, pageParams.PageSize, nil

}

// GetRolesOptions 角色下拉列表
func GetRolesOptions() ([]SysRoleOptions, error) {

	//==>  Preparing: SELECT id, name FROM sys_role WHERE is_deleted = 0 AND (code <> ?) ORDER BY sort ASC
	//==> Parameters: ROOT(String)

	var roleOptions []SysRoleOptions

	// 主查询用于获取分页数据
	model := dao.Db.Debug().Table("sys_role").
		Select("id, name").
		Where("is_deleted = 0").
		Where("code <> ?", "root")

	// 执行查询获取分页数据
	if err := model.Scan(&roleOptions).Error; err != nil {
		return nil, err
	}

	return roleOptions, nil

}

// AddRole 新增角色
func AddRole(role RoleForm) (int64, error) {

	//==>  Preparing: INSERT INTO sys_role ( name, code, sort, status, data_scope, create_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ? )
	//==> Parameters: 管理员21(String), ADMIN21(String), 1(Integer), 1(Integer), 1(Integer), 2024-10-11T19:32:07.863432(LocalDateTime), 2024-10-11T19:32:07.863464(LocalDateTime)

	var insertData SysRoleAddData
	cpErr := copier.Copy(&insertData, &role)
	if cpErr != nil {
		return insertData.ID, cpErr
	}

	insertData.CreateTime = time.Now()
	insertData.UpdateTime = time.Now()

	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
	err := dao.Db.Table("sys_role").Create(&insertData).Error // 通过数据的指针来创建
	return insertData.ID, err
}

// GetRoleFromById 角色表单数据
func GetRoleFromById(id string) (SysRoleFormData, error) {

	var result SysRoleFormData
	//==>  Preparing: SELECT id, name, code, sort, status, data_scope, create_by, update_by, create_time, update_time, is_deleted FROM sys_role WHERE id = ? AND is_deleted = 0
	//==> Parameters: 2(Long)
	err := dao.Db.Debug().Table("sys_role").
		Select("id, name, code, sort, status, data_scope, create_by, update_by, create_time, update_time, is_deleted").
		Where("is_deleted = 0 AND (id = ?)", id).
		First(&result).Error

	if err != nil {
		// 判断如果查询不到记录返回一个空对象
		//if errors.Is(err, gorm.ErrRecordNotFound) {
		//	fmt.Println("########gorm.ErrRecordNotFound")
		//	return struct{}{}, nil
		//}

		return result, err
	}

	// 检查结果的 ID 是否为零值
	//if result.ID == 0 {
	//	// 返回一个空对象指针
	//	return &SysRoleFormData{}, nil
	//}

	return result, nil

}

// EditRole 修改角色
func EditRole(role SysRoleFormData, roleId string) error {
	var editData SysRoleEditData

	cpErr := copier.Copy(&editData, &role)
	if cpErr != nil {
		return cpErr
	}

	editData.UpdateTime = time.Now()

	err := dao.Db.Debug().Table("sys_role").
		Where("is_deleted = 0").
		Where("id = ?", roleId).
		Updates(&editData).Error

	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
	return err
}

// DelRoleSoftByIds 批量删除（软删除）
func DelRoleSoftByIds(ids string) error {

	// UPDATE sys_role SET update_time = ?, is_deleted = 1 WHERE id = ? AND is_deleted = 0
	err := dao.Db.Debug().Table("sys_role").
		Where("is_deleted = 0").
		Where("id IN (?)", ids).
		Updates(map[string]interface{}{"update_time": time.Now(), "is_deleted": 1}).Error
	return err
}

// EditRoleStatus 修改用户状态
func EditRoleStatus(query SysStatus, roleId string) error {

	err := dao.Db.Debug().Table("sys_role").
		Where("is_deleted = 0").
		Where("id = ?", roleId).
		Updates(map[string]interface{}{"status": query.Status}).Error
	return err
}
